package com.caifu.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

/**
 * @Auther: Lyf
 * @Date: 2020/7/8 09:36
 * @Description:
 */
@Component
public class DateUtil {

    private static String path;

    //分页数量
    public final static int PAGE_SIZE_FIVE=5;

    public final static int PAGE_SIZE_SIX=6;

    public final static int PAGE_SIZE_TEN=10;

    public final static String DATE_PATTERN_YYYYMMDDHHMMSS_01="yyyy-MM-dd HH:mm:ss";

    /**
     * 日期转字符串
     * @auther: Lyf
     * @param date	  date参数
     * @param format  格式类型
     * @return 返回格式化后的字符串
     */
    public static String dateToString(Date date, String format){
        try {
            if(date == null){
                date = new Date();
            }
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return sdf.format(date);
        }catch (Exception e){
            return  "";
        }
    }

    /**
     * 字符串转日期
     * @auther: Lyf
     * @param date	 date参数
     * @param format  格式类型
     * @return 返回date
     */
    public static Date stringToDate(String date,String format){
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return sdf.parse(date);
        }catch (Exception e){
            return null;
        }
    }

    /**
     * 功能描述: 日期推算
     *
     * @auther: Lyf
     * @date: 2020/7/8 10:23
     * @param: date 需要前推的日期（传递null默认当前日期）
     * @param: days 需要前推的天数
     * @return:
     */
    public static String dateCalculation(Date date,int days){
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        if(date == null) {
            date = new Date();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, days);
        date = (Date) calendar.getTime();
        String day = df.format(date);
        return day;
    }

    /**
     * 功能描述: 日期推算
     *
     * @auther: Lyf
     * @date: 2020/7/8 10:23
     * @param: date 需要前推的日期（传递null默认当前日期）
     * @param: days 需要前推的年
     * @return:
     */
    public static String dateCalculation_year(Date date,int years){
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        if(date == null) {
            date = new Date();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, years);
        date = (Date) calendar.getTime();
        String day = df.format(date);
        return day;
    }

    /**
     * 功能描述: 日期推算
     *
     * @auther: Lyf
     * @date: 2020/7/8 10:23
     * @param: date 需要前推的日期字符串
     * @param: format 需要前推的日期字符串格式
     * @param: days 需要前推的天数
     * @return:
     */
    public static String dateCalculation(String date,String format,int days){
        //DateFormat df = new SimpleDateFormat("YYYY-MM-DD");
        DateFormat dsf = new SimpleDateFormat(format);
        if(StringUtils.isNotBlank(date)) {
            try {
                Date d = dsf.parse(date);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(d);
                calendar.add(Calendar.DAY_OF_MONTH, days);
                d = (Date) calendar.getTime();
                String day = dsf.format(d);
                return day;
            }catch (Exception e){
                return "";
            }
        }else{
            return "";
        }
    }

    /**
     * 功能描述: 生成随机数字和字母
     *
     * @auther: Lyf
     * @date: 2020/7/8 10:38
     * @param: length  生成位数
     * @return:
     */
    public static String getStringRandom(int length) {
        String val = "";
        Random random = new Random();
        //参数length，表示生成几位随机数
        for(int i = 0; i < length; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if( "char".equalsIgnoreCase(charOrNum) ) {
                //输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char)(random.nextInt(26) + temp);
            } else if( "num".equalsIgnoreCase(charOrNum) ) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }

    /**
     * 功能描述: 根据uuid生成不重复的文件名
     *
     * @auther: Lyf
     * @date: 2020/7/20 10:26
     * @param:
     * @return:
     */
    public static String getNewFileName(String fileName){
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        return UUID.randomUUID().toString().replace("-","") + suffix;
    }

    //格式化日期格式8位  yyyyMMdd---------->yyyy-MM-dd
    public static String dateFormat(String dateTime){
        if(dateTime == null){
            return "";
        }
        SimpleDateFormat sdf1=new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd");
        try {
            return sdf2.format(sdf1.parse(dateTime));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }
    //格式化日期格式  hhmmss---------->HH:mm:ss
    public static String timeFormat(String dateTime){
        SimpleDateFormat sdf1=new SimpleDateFormat("HHmmss");
        SimpleDateFormat sdf2=new SimpleDateFormat("HH:mm:ss");
        try {
            return sdf2.format(sdf1.parse(dateTime));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }





    // 根据年月日计算年龄,birthTimeString:"1994-11-14"
    public static int getAgeFromBirthTime(String birthTimeString) {
        // 先截取到字符串中的年、月、日
        String strs[] = birthTimeString.trim().split("-");
        int selectYear = Integer.parseInt(strs[0]);
        int selectMonth = Integer.parseInt(strs[1]);
        int selectDay = Integer.parseInt(strs[2]);
        // 得到当前时间的年、月、日
        Calendar cal = Calendar.getInstance();
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH) + 1;
        int dayNow = cal.get(Calendar.DATE);

        // 用当前年月日减去生日年月日
        int yearMinus = yearNow - selectYear;
        int monthMinus = monthNow - selectMonth;
        int dayMinus = dayNow - selectDay;

        int age = yearMinus;// 先大致赋值
        if (yearMinus < 0) {// 选了未来的年份
            age = 0;
        } else if (yearMinus == 0) {// 同年的，要么为1，要么为0
            if (monthMinus < 0) {// 选了未来的月份
                age = 0;
            } else if (monthMinus == 0) {// 同月份的
                if (dayMinus < 0) {// 选了未来的日期
                    age = 0;
                } else if (dayMinus >= 0) {
                    age = 1;
                }
            } else if (monthMinus > 0) {
                age = 1;
            }
        } else if (yearMinus > 0) {
            if (monthMinus < 0) {// 当前月>生日月
            } else if (monthMinus == 0) {// 同月份的，再根据日期计算年龄
                if (dayMinus < 0) {
                } else if (dayMinus >= 0) {
                    age = age + 1;
                }
            } else if (monthMinus > 0) {
                age = age + 1;
            }
        }
        return age;
    }

    /**
     * 获取当前日期
     *
     * 2020年8月14日
     * codeBy szt
     */
    public static String currentDate(String format){
        Date date=new Date();
        if(StringUtils.isBlank(format)){
            format="yyyyMMdd";
        }
        SimpleDateFormat dateFormat=new SimpleDateFormat(format);
        return dateFormat.format(date);
    }


    /**
     * 获取当前时间
     * 2020年8月14日
     * codeBy szt
     */
    public static String currentDateTime(String format){
        Date date=new Date();
        if(StringUtils.isBlank(format)){
            format="yyyyMMddHHmmss";
        }
        SimpleDateFormat dateFormat=new SimpleDateFormat(format);
        return dateFormat.format(date);
    }

    /**
     * 功能描述: 14位时间转时间戳
     * @Param:  [val]
     * @Author: szt
     * @Date:   2020/10/13
     */
    public static long timeToStamp(String val,String format) throws ParseException {
        if(StringUtils.isBlank(format)){
            format="yyyyMMddHHmmss";
        }
        DateFormat dsf = new SimpleDateFormat(format);
        Date d = dsf.parse(val);
        return d.getTime();
    }


    /**
     * 功能描述: 获取本周第一天或最后一天
     * @Param:  [type] 0-第一天   1-第七天
     * @Author: szt
     * @Date:   2020/10/13
     */
    public static String getThisWeekOfSpecialDay(int type) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Calendar calendar = Calendar.getInstance();
        if(type==0){
            calendar.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY);
        }else if(type==1){
            calendar.set(Calendar.DAY_OF_WEEK, calendar.getActualMaximum(Calendar.DAY_OF_WEEK));
            calendar.add(Calendar.DAY_OF_WEEK, 1);
        }
        return format.format(calendar.getTime());
    }

    /**
     * 功能描述: 获取本月第一天或最后一天
     * @Param:  [type] 0-第一天   1-第七天
     * @Author: szt
     * @Date:   2020/10/13
     */
    public static String getThisMonthOfSpecialDay(int type){
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Calendar calendar=Calendar.getInstance();
        if(type==0){
            calendar.set(Calendar.DAY_OF_MONTH, 1);
        }else if(type==1){
            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        }
        return format.format(calendar.getTime());
    }

    /**
     * 计算两个日期之间相差的天数
     * @param smdate 较小的时间
     * @param bdate  较大的时间
     * @return 相差天数
     * @throws ParseException
     */
    public static int daysBetween(Date smdate,Date bdate) throws ParseException
    {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        smdate=sdf.parse(sdf.format(smdate));
        bdate=sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600*24);

        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     *字符串的日期格式的计算
     */
    public static int daysBetween(String smdate,String bdate) throws ParseException{
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(smdate));
        long time1 = cal.getTimeInMillis();
        cal.setTime(sdf.parse(bdate));
        long time2 = cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600*24);

        return Integer.parseInt(String.valueOf(between_days));
    }

}
